package top.shaoxia.pwdm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

/**
 * @author wjc
 * @date 2022/3/28
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //默认角色，拥有所有权限
    private static final String ROLE_ADMIN = "ADMIN";
    //默认用户
    private static final String USER_ADMIN = "admin";
    //默认密码:123456
    private static final String DEFAULT_PWD = "$2a$12$Rqo.1b8.v4.DhAwmQjPxFejuRYTLtrMjYTGmfPfH1Z3j7lKbcoX8C";

    @Autowired
    private DataSource dataSource;

    @Bean
    public UserDetailsService userDetailsService() {
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);
        if (!manager.userExists(USER_ADMIN)) {
            manager.createUser(User.withUsername(USER_ADMIN).password(DEFAULT_PWD).roles(ROLE_ADMIN).build());
        }
        return manager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(12);
        return bCryptPasswordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/*.html", "/*.ico", "/*.png", "/*.json", "/assets/**").permitAll()//静态资源可访问
                .antMatchers("/api/auth").permitAll()//获取登录信息可访问
                .antMatchers("/api/version").permitAll()//获取版本信息
                .antMatchers("/api/**").hasRole(ROLE_ADMIN)
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/api/login")//登录表单处理url，spring内部进行处理
                .failureForwardUrl("/api/auth")//登录失败转发到的url
                .successForwardUrl("/api/auth")//登录成功转发到的url
                .permitAll()
                .and().csrf().disable();
        http.logout().logoutUrl("/api/logout").logoutSuccessUrl("/").invalidateHttpSession(true);
    }
}
